<template>
	<div class="admin-container">
		<!-- 搜索栏 -->
		<div class="search-bar">
			<el-row :gutter="20">
				<el-col :span="6">
					<el-input v-model="searchParams.orderId" placeholder="请输入订单编号" clearable
						@keyup.enter.native="searchByOrderId">
					</el-input>
				</el-col>
				<el-col :span="4">
					<el-date-picker v-model="searchParams.date" type="date" placeholder="选择日期" value-format="yyyy-MM-dd"
						@change="searchByDate">
					</el-date-picker>
				</el-col>
				<el-col :span="3">
					<el-select v-model="searchParams.status" placeholder="请选择状态" clearable @change="searchByStatus">
						<el-option label="全部" value="全部"></el-option>
						<el-option label="未支付" value="未支付"></el-option>
						<el-option label="未发货" value="未发货"></el-option>
						<el-option label="已完成" value="已完成"></el-option>
						<el-option label="退款中" value="退款中"></el-option>
						<el-option label="已退款" value="已退款"></el-option>
						<!-- <el-option label="已取消" value="已取消"></el-option> -->
					</el-select>
				</el-col>
				

				<el-col :span="12">
					<el-button type="primary" @click="searchByOrderId">搜索订单编号</el-button>
					<el-button type="success" @click="showAddDialog">新增</el-button>
				</el-col>
			</el-row>
		</div>
		<div class="operation-bar">
			<el-button size="mini" @click="batchMarkPaid">已支付</el-button>
			<el-button size="mini" @click="batchMarkShipped">已发货</el-button>
			<el-button size="mini" @click="batchty">已完成</el-button>
			<el-button size="mini" @click="refund">同意退款</el-button>
			<el-button size="mini" @click="refund2">取消订单</el-button>
			<el-button size="mini" @click="batchDelete">删除</el-button>
		</div>
		<!-- 信息展示区 -->
		<div class="table-container">
			<el-table :data="tableData" style="width: 100%" border v-if="tableData.length > 0"
				@selection-change="handleSelectionChange">
				<el-table-column type="selection" width="55">
				</el-table-column>
				<el-table-column prop="ordernumber" label="订单编号" width="240">
				</el-table-column>
				<el-table-column prop="phone" label="电话号码" width="180">
				</el-table-column>
				<el-table-column prop="total_amount" label="总金额" width="100" >
				</el-table-column>
				<el-table-column prop="discount" label="折扣" width="100">
					<template slot-scope="scope">
						{{ scope.row.discount }}%
					</template>
				</el-table-column>
				<el-table-column prop="payment_method" label="支付方式" width="100">
				</el-table-column>
				<el-table-column prop="status" label="状态" width="80">
				</el-table-column>
				<el-table-column prop="address_line" label="配送地址">
					<template slot-scope="scope">
						{{ scope.row.address_line1 + scope.row.address_line2 }}
					</template>
				</el-table-column>
				<el-table-column prop="create_time" label="创建时间">
					<template slot-scope="scope">
						{{ formatDate(scope.row.create_time) }}
					</template>
				</el-table-column>
				<el-table-column prop="update_time" label="更新时间">
					<template slot-scope="scope">
						{{ formatDate(scope.row.update_time) }}
					</template>
				</el-table-column>
				<el-table-column label="操作" width="170">
					<template slot-scope="scope">
						<el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
						<el-button size="mini" @click="handleDetail(scope.row)">详细信息</el-button>
					</template>
				</el-table-column>
			</el-table>
			<div v-else class="no-data">
				<p>没有找到匹配的数据</p>
			</div>
		</div>
		<!-- 分页组件 -->
		<div class="pagination-container">
			<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
				:current-page.sync="currentPage" :page-size.sync="pageSize"
				layout="total, sizes, prev, pager, next, jumper" :total="allData.length">
			</el-pagination>
		</div>
		<!-- 编辑对话框 -->
		<el-dialog title="编辑订单" :visible.sync="editDialogVisible" width="30%">
			<el-form :model="currentRow" :rules="editRules" ref="editForm">
				<el-form-item label="订单编号" prop="ordernumber">
					<el-input v-model="currentRow.ordernumber" readonly></el-input>
				</el-form-item>
				<el-form-item label="用户名" prop="name">
					<el-input v-model="currentRow.name"></el-input>
				</el-form-item>
				<el-form-item label="总金额" prop="total_amount" >
					<el-input v-model="currentRow.total_amount" readonly></el-input>
				</el-form-item>
				<el-form-item label="支付方式" prop="payment_method">
					<el-select v-model="currentRow.payment_method" placeholder="请选择支付方式">
						<el-option label="微信支付" value="微信支付"></el-option>
						<el-option label="支付宝支付" value="支付宝支付"></el-option>
						<el-option label="现金支付" value="现金支付"></el-option>
					</el-select>
				</el-form-item>
<!-- 				<el-form-item label="状态" prop="status">
					<el-input v-model="currentRow.status"></el-input>
				</el-form-item> -->
				<el-form-item label="状态" prop="status">
					<el-select v-model="currentRow.status" placeholder="请选择状态">
						<el-option label="未支付" value="未支付"></el-option>
						<el-option label="未发货" value="未发货"></el-option>
						<el-option label="已完成" value="已完成"></el-option>
						<el-option label="退款中" value="退款中"></el-option>
						<el-option label="已退款" value="已退款"></el-option>
						<el-option label="已取消" value="已取消"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="区域地址">
					<el-input v-model="currentRow.address_line1"></el-input>
				</el-form-item>
				<el-form-item label="详细地址">
					<el-input v-model="currentRow.address_line2"></el-input>
				</el-form-item>
				<el-form-item label="电话号码">
					<el-input v-model="currentRow.phone"></el-input>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="editDialogVisible = false">取消</el-button>
				<el-button type="primary" @click="handleUpdate">更新</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
	import axios from 'axios';
	import {
		Input,
		Row,
		Col,
		Button,
		Select,
		Option,
		Table,
		TableColumn,
		Dialog,
		Form,
		FormItem,
		Pagination,
		Message,
		DatePicker
	} from 'element-ui';

	export default {
		name: 'OrderTable',
		components: {
			'el-input': Input,
			'el-row': Row,
			'el-col': Col,
			'el-button': Button,
			'el-select': Select,
			'el-option': Option,
			'el-table': Table,
			'el-table-column': TableColumn,
			'el-dialog': Dialog,
			'el-form': Form,
			'el-form-item': FormItem,
			'el-pagination': Pagination,
			'el-date-picker': DatePicker
		},
		data() {
			return {
				allData: [],
				tableData: [],
				searchParams: {
					orderId: '',
					status: '全部',
					date: ''
				},
				addDialogVisible: false,
				editDialogVisible: false,
				currentRow: {
					id: '',
					name: '',
					total_amount: '',
					status: '',
					payment_method: '',
					address_line1: '',
					address_line2: '',
					phone: '',
					useraddress_id: ''
				},
				editRules: {
					ordernumber: [{
						required: true,
						message: '订单编号不能为空',
						trigger: 'blur'
					}],
					name: [{
							required: true,
							message: '用户名不能为空',
							trigger: 'blur'
						},
						{
							min: 2,
							max: 10,
							message: '用户名长度在 2 到 10 个字符',
							trigger: 'blur'
						}
					],
					total_amount: [{
							required: true,
							message: '总金额不能为空',
							trigger: 'blur'
						},
						{
							type: 'number',
							message: '总金额必须为数字',
							trigger: 'blur'
						}
					],
					payment_method: [{
						required: true,
						message: '支付方式不能为空',
						trigger: 'blur'
					}],
					status: [{
						required: true,
						message: '状态不能为空',
						trigger: 'blur'
					}],
					address_line1: [{
						required: true,
						message: '区域地址不能为空',
						trigger: 'blur'
					}],
					address_line2: [{
						required: true,
						message: '详细地址不能为空',
						trigger: 'blur'
					}],
					phone: [{
							required: true,
							message: '电话号码不能为空',
							trigger: 'blur'
						},
						{
							pattern: /^1[3-9]\d{9}$/,
							message: '电话号码格式不正确',
							trigger: 'blur'
						}
					]
				},
				currentPage: 1,
				pageSize: 10,
				selectedRows: []
			};
		},
		created() {
			this.fetchData();
		},
		methods: {
			fetchData() {
				const token = localStorage.getItem('Authorization');
				if (!token) {
					this.$message.error('未授权访问');
					return;
				}
				const headers = {
					'Content-Type': 'application/json',
					'Authorization': token
				};
				axios.get('http://localhost:8887/Order/findAll', {
						headers
					})
					.then(response => {
						if (response.data.code === 200) {
						        this.allData = response.data.data;
						        this.sortTableByUpdateTime(); 
						        this.tableData = this.allData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
						      } else {
							this.$message.error('获取数据失败: ' + response.data.message);
						}
					})
					.catch(error => {
						console.error('请求失败:', error);
						this.$message.error('请求失败，请检查网络或联系管理员');
					});
			},
			formatDate(value) {
				const date = new Date(value);
				return new Intl.DateTimeFormat('zh-CN', {
					year: 'numeric',
					month: '2-digit',
					day: '2-digit',
					hour: '2-digit',
					minute: '2-digit',
					second: '2-digit',
					hour12: false
				}).format(date);
			},
			sortTableByUpdateTime() {
			  this.allData.sort((a, b) => {
			    return new Date(b.update_time) - new Date(a.update_time);
			  });
			},
			searchByOrderId() {
				const token = localStorage.getItem('Authorization');
				const headers = {
					'Content-Type': 'application/x-www-form-urlencoded',
					'Authorization': token,
				};
				axios.get('http://localhost:8887/Order/selectordernumber', {
						headers,
						params: {
							ordernumber: this.searchParams.orderId
						}
					})
					.then(response => {
						if (response.data.code === 200) {
							this.allData = response.data.data;
							this.sortTableByUpdateTime();
							this.tableData = this.allData.slice((this.currentPage - 1) * this.pageSize, this
								.currentPage * this.pageSize);
							
						} else {
							this.fetchData();
							this.$message.error(response.data.message || '未找到匹配的订单编号');
							this.tableData = [];
						}
					})
					.catch(error => {
						this.fetchData();
						console.error('请求失败:', error);
						this.$message.error('未找到匹配的订单编号');
					});
			},
			searchByStatus() {
				if (this.searchParams.status === '全部') {
					this.fetchData();
				} else {
					const token = localStorage.getItem('Authorization');
					const headers = {
						'Content-Type': 'application/x-www-form-urlencoded',
						'Authorization': token,
					};
					axios.get('http://localhost:8887/Order/selectstatus', {
							headers,
							params: {
								status: this.searchParams.status
							}
						})
						.then(response => {
							if (response.data.code === 200 && response.data.data.length > 0) {
								this.allData = response.data.data;
								this.sortTableByUpdateTime(); 
								this.tableData = this.allData.slice((this.currentPage - 1) * this.pageSize, this
									.currentPage * this.pageSize);
								
							} else {
								this.$message.error(response.data.message || '未找到匹配的订单状态');
								this.tableData = []; // 清空表格数据
							}
						})
						.catch(error => {
							console.error('请求失败:', error);
							this.$message.error('请求失败，请检查网络或联系管理员');
						});
				}
			},
			searchByDate(value) {
				if (value) {
					this.fetchDataByDate(value);
				}
			},
			fetchDataByDate(date) {
				const token = localStorage.getItem('Authorization');
				const headers = {
					'Content-Type': 'application/json',
					'Authorization': token
				};
				axios.get('http://localhost:8887/Order/selectorderbydate', {
						params: {
							date
						},
						headers
					})
					.then(response => {
						if (response.data.code === 200) {
							this.allData = response.data.data;
							this.sortTableByUpdateTime(); 
							this.tableData = this.allData.slice((this.currentPage - 1) * this.pageSize, this
								.currentPage * this.pageSize);
							
						} else {
							this.$message.error('获取数据失败: ' + response.data.message);
						}
					})
					.catch(error => {
						console.error('请求失败:', error);
						this.$message.error('请求失败，请检查网络或联系管理员');
					});
			},
			handleEdit(row) {
				if (row) {
					this.currentRow = {
						...row
					};
					this.editDialogVisible = true;
				} else {
					console.error('Error: Row data is null');
				}
			},
			handleDelete(id) {
				this.$confirm('确认删除这条记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					const token = localStorage.getItem('Authorization');
					const headers = {
						'Content-Type': 'application/x-www-form-urlencoded',
						'Authorization': token
					};
					axios.post('http://localhost:8887/Order/delete', {
							id
						}, {
							headers
						})
						.then(response => {
							if (response.data.code === 200) {
								this.$message.success('删除成功');
								this.fetchData(); // 重新加载数据
							} else {
								this.$message.error('删除失败: ' + response.data.message);
							}
						})
						.catch(error => {
							console.error('请求失败:', error);
							this.$message.error('请求失败，请检查网络或联系管理员');
						});
				}).catch(() => {
					this.$message.info('已取消删除');
				});
			},
			handleDetail(row) {
				if (row && row.id) {
					this.$router.push({
						name: 'OrderDetails',
						params: {
							id: row.id
						}
					});
					console.log(row.id)
				} else {
					console.error('Error: Row data or id is null');
				}
			},
			handleUpdate() {
				this.$refs.editForm.validate((valid) => {
					if (valid) {
						const token = localStorage.getItem('Authorization');
						const headers = {
							'Content-Type': 'application/json',
							'Authorization': token
						};
						axios.post('http://localhost:8887/Order/adminupdate', this.currentRow, {
								headers
							})
							.then(response => {
								if (response.data.code === 200) {
									this.$message.success('更新成功');
									this.editDialogVisible = false;
									this.fetchData(); // 重新加载数据
								} else {
									this.$message.error('更新失败: ' + response.data.message);
								}
							})
							.catch(error => {
								console.error('请求失败:', error);
								this.$message.error('请求失败，请检查网络或联系管理员');
							});
					} else {
						this.$message.error('表单验证失败');
					}
				});
			},
			showAddDialog() {
				this.$router.push('/order/Addorder');
			},
			handleSizeChange(newSize) {
			  this.pageSize = newSize;
			  this.sortTableByUpdateTime(); // 分页变化后重新排序
			  this.tableData = this.allData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
			},
			
			handleCurrentChange(newPage) {
			  this.currentPage = newPage;
			  this.sortTableByUpdateTime(); // 分页变化后重新排序
			  this.tableData = this.allData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
			},
			handleSelectionChange(val) {
				this.selectedRows = val;
			},
			batchRefund() {
				this.batchUpdateStatus('退款中');
			},
			batchMarkPaid() {
				this.batchUpdateStatus('未发货');
			},
			batchMarkShipped() {
				this.batchUpdateStatus('已发货');
			},
			batchty() {
				this.batchUpdateStatus('已完成');
			},
			refund() {
				this.batchUpdateStatus('已退款');
			},
			refund2() {
				this.batchUpdateStatus('已取消');
			},
			batchDelete() {
				this.confirmAndDelete();
			},
			batchUpdateStatus(newStatus) {
				this.$confirm('确认执行此批量操作吗?', '提示', {
					type: 'warning'
				}).then(() => {
					const ids = this.selectedRows.map(row => row.id);
					if (ids.length === 0) {
						this.$message.warning('请选择要操作的行');
						return;
					}
					const payload = {
						ids: ids,
						status: newStatus
					};
					const token = localStorage.getItem('Authorization');
					const headers = {
						'Content-Type': 'application/json',
						'Authorization': token
					};
					axios.post('http://localhost:8887/Order/batchUpdateStatus', payload, {
							headers
						})
						.then(response => {
							if (response.data.code === 200) {
								this.$message.success(response.data.message);
								this.fetchData(); // 重新加载数据
							} else {
								this.$message.error(response.data.message);
							}
						})
						.catch(error => {
							console.error('请求失败:', error);
							this.$message.error('请求失败，请检查网络或联系管理员');
						});
				}).catch(() => {
					this.$message.info('已取消操作');
				});
			},
			confirmAndDelete() {
				this.$confirm('确认执行此批量操作吗?', '提示', {
					type: 'warning'
				}).then(() => {
					const ids = this.selectedRows.map(row => row.id);
					if (ids.length === 0) {
						this.$message.warning('请选择要操作的行');
						return;
					}
					const payload = {
						ids: ids,
					};
					const token = localStorage.getItem('Authorization');
					const headers = {
						'Content-Type': 'application/json',
						'Authorization': token
					};
					axios.post('http://localhost:8887/Order/admindelete', payload, {
							headers
						})
						.then(response => {
							if (response.data.code === 200) {
								this.$message.success(response.data.message);
								this.fetchData(); // 重新加载数据
							} else {
								this.$message.error(response.data.message);
							}
						})
						.catch(error => {
							console.error('请求失败:', error);
							this.$message.error('请求失败，请检查网络或联系管理员');
						});
				}).catch(() => {
					this.$message.info('已取消操作');
				});
			},
		},
	};
</script>

<style scoped>
	.admin-container {
		padding: 20px;
		max-width: 100%;
		overflow-x: auto;
	}

	.search-bar {
		margin-bottom: 20px;
	}

	.search-bar .el-row {
		display: flex;
		justify-content: space-between;
	}

	.search-bar .el-button {
		margin-left: 10px;
	}

	.table-container {
		margin-top: 20px;
		overflow-x: auto;
	}

	.no-data {
		text-align: center;
		padding: 20px;
	}

	.pagination-container {
		margin-top: 20px;
		text-align: left;
	}

	.dialog-footer {
		text-align: right;
	}

	.el-dialog__body {
		padding: 20px;
	}

	.el-form-item {
		margin-bottom: 20px;
	}

	.el-form-item__label {
		font-weight: bold;
	}

	.el-button--primary {
		background-color: #13ce66;
		border-color: #13ce66;
	}

	.el-button--primary:hover {
		background-color: #11b55e;
		border-color: #11b55e;
	}
</style>